//
//  HJComposeView.swift
//  zhangmiSinweibo
//
//  Created by zhangmi on 16/5/29.
//  Copyright © 2016年 Paramount Pictures. All rights reserved.
//

import UIKit
import SnapKit

class HJComposeView: UIView {
    
    //保存参数,方便其他地方使用
    weak var target: UIViewController?
    
    func show(targetVC target: UIViewController) {
        self.target = target
        //添加视图
        target.view.addSubview(self)
    }

    
    override init(frame: CGRect) {
        //指定大小
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //从父视图移除
        self.removeFromSuperview()
        for (index,btn) in buttons.reverse().enumerate() {
            startAnimation(btn, index: index, offset: 350)
        }
    }
    
    //将要移动到父视图上之后开始做动画
    override func  willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(superview)
        
        for(index,btn) in buttons.enumerate() {
            
            startAnimation(btn, index: index, offset: -350)
        }
    }
    
    private func startAnimation(btn: HJComposeButton, index: Int, offset: CGFloat) {
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: { 
            //修改按钮的y值
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            }, completion: { (_) in
                if offset > 0 {
                    //移除
                    self.removeFromSuperview()
                }
        })
    }
    
    
    
    
    //设置界面
    private func setupUI() {
        //设置背景颜色
        backgroundColor = UIColor.redColor()
        addSubview(backImageView)

        
        addSubview(sloganImageView)
        
        //设置约束
        sloganImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }
        //添加留个按钮
        addChildButtons()
    }
    
    private func addChildButtons() {
//        let count = 6
        let count = composeItems.count
        //指定按钮的大小
        let w: CGFloat = 80
        let h: CGFloat = 120
        let margin: CGFloat = (ScreenWidth - 3 * w) / 4
//        for i in 0..<6 {
        for i in 0..<count {
        
            let btn = HJComposeButton()
            
            //设置按钮的图片和文字的大小
            let item = composeItems[i]
            
            btn.composeItem = item
            //添加点击的事件
            btn.addTarget(self, action: #selector(HJComposeView.btnDidClick(_:)), forControlEvents: .TouchUpInside)
            

            let row = i / 3
            let col = i % 3
//            self .addSubview(btn)
            let x = CGFloat(col) * (margin + w) + margin
            let y = CGFloat(row) * (margin + h) + ScreenHeight
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            
            self .addSubview(btn)
            
            buttons.append(btn)
        }
    }
    
    //被点击的按钮放大
    //其他按的按钮缩小
    @objc private func btnDidClick(btn: HJComposeButton) {
        for button in buttons {
            //判断是否是点击的按钮
            var scale: CGFloat = 0
            if button == btn {
                //放大
                scale = 8.0
            }else {
                //缩小
                scale = 0.2
            }
            
            UIView.animateWithDuration(0.55, animations: {
                //修改形变
                button.alpha = 0
                button.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) in
                    print("72变")
                    //跳转界面
            })
        }
        //页面跳转
        //获取控制器的名称
        print(btn.composeItem)
        guard let target = btn.composeItem?.target else {
            return
        }
//        //就是根据字符串对应的类型来获取控制器对应的类型
//        let type = NSClassFromString(target) as! UIViewController.Type
//        //初始化控制器
//        let vc = type.init()
//        let nav = UINavigationController(rootViewController: vc)
//        //页面跳转.视图不能跳转
//        self.target?.presentViewController(nav, animated: true, completion: { 
//            self.removeFromSuperview()
//        })
        
        
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(time_t, dispatch_get_main_queue()) {
            //就是根据字符串对应的类型来获取控制器对应的类型
            let type = NSClassFromString(target) as! UIViewController.Type
            //初始化控制器
            let vc = type.init()
            let nav = UINavigationController(rootViewController: vc)
            //页面跳转.视图不能跳转
            self.target?.presentViewController(nav, animated: true, completion: {
                self.removeFromSuperview()
            })
        }
    }
    
    
    
    
    //懒加载控件
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage.snapShotCurrentWindow().applyLightEffect())
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    //按钮数组保存按钮
    private lazy var buttons: [HJComposeButton] = [HJComposeButton]()
    
    private lazy var composeItems: [HJComposeItem] = {
        var array = [HJComposeItem]()
        //获取文件的数据
        //1.文件路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        //读取路径下的数据
        let itemArray = NSArray(contentsOfFile: path) as! [[String : AnyObject]]
        //遍历数组, 字典转模型
        for item in itemArray {
            let composeItem = HJComposeItem(dict: item)
            array.append(composeItem)
        }
        return array
        
    }()
    
}

